package com.ktjiaoyu.controller;

import com.ktjiaoyu.entity.SysUser;
import com.ktjiaoyu.service.SysUserService;
import com.ktjiaoyu.utils.Constants;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class LoginController extends BaseController {
    @Autowired
    private SysUserService sysUserService;
    @GetMapping("/login")
    public String toLogin(){
        return "forward:/login.jsp";
    }
    @PostMapping(value = "/login")
    public String login(@RequestParam("account")String account, @RequestParam("password")String password, HttpServletRequest request, HttpSession session){
        SysUser loginUser= sysUserService.login(account,password);
        if (loginUser!=null){
            session.setAttribute(Constants.SESSION_USER,loginUser);
            return "redirect:/main/index";
        }else {
            request.setAttribute(Constants.REQUEST_ERROR,"用户名或者密码错误");
            return "forward:/login.jsp";
        }
    }
//退出
//    @ExceptionHandler(value = RuntimeException.class)
//    public String handleException(RuntimeException e,HttpServletRequest request){
//        request.setAttribute(Constants.REQUEST_ERROR,e);
//        return "500";
//    }
    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "redirect:/login.jsp";
    }
    @GetMapping("/main/index")
    public String index(){
        return "index";
    }
}
